package com.voltmao.webpro.utils.http;


import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;


public class PostUtil {
    /**
     * 发送文件post
     */
    public static String sendPostWithFile(String url, File file){
        //构建HttpClient对象
        CloseableHttpResponse response = null;
        CloseableHttpClient client = HttpClients.createDefault();
        //构建POST请求
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
        httpPost.setConfig(requestConfig);
        try {
            //构建文件体
            HttpEntity httpEntity = MultipartEntityBuilder.create()
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .addPart("files", new FileBody(file))
                    .build();
            //必须是这样拿到头
            httpPost.addHeader(httpEntity.getContentType());
            httpPost.setEntity(httpEntity);
            //发送请求
            response = client.execute(httpPost);
            httpEntity = response.getEntity();
            if(httpEntity != null){
                String resultStr = EntityUtils.toString(httpEntity, "utf-8");
                return resultStr;
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (response != null) {
                try {
                    response.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
